package com.freexiaoyu.cloud.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class NetUtil {
	
    /**
     * 网络连接检测
     * @param ctx
     * @return
     */
    public static boolean isNetworkAvailable(Context ctx) {   
    	boolean netstatus = false;
        try {   
            ConnectivityManager cm = (ConnectivityManager) ctx   
                    .getSystemService(Context.CONNECTIVITY_SERVICE);   
            NetworkInfo info = cm.getActiveNetworkInfo();   
            if(info != null && info.isConnected()){
            	netstatus = true;
            }   
        } catch (Exception e) {   
            e.printStackTrace();   
            netstatus = false;   
        } 
        return netstatus;
    } 
    

    
    /**
	* 获取当前的网络状态 -1：没有网络     1：WIFI网络    2：wap网络    3：net网络 
	* @param context 
	* @return 
	*/ 
	public static int getAPNType(Context context){ 
		int netType = -1; 
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
		if(networkInfo==null){ 
			return netType; 
		} 
		int nType = networkInfo.getType(); 
		if(nType==ConnectivityManager.TYPE_MOBILE){ 
		
			if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet")){ 
				netType = 3; 
			} 
			else{ 
				netType = 2; 
			} 
		} 
		else if(nType==ConnectivityManager.TYPE_WIFI){ 
			netType = 1; 
		} 
		return netType; 
	}
	
    
    
    /**
     * 通过GPRS获取本地IP
     * @return
     */
	public static String getLocalIpAddress(){
		String ip = "127.0.0.1";
        try
        {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
            {
               NetworkInterface intf = en.nextElement();
               for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
               {
                   InetAddress inetAddress = enumIpAddr.nextElement();
                   if (!inetAddress.isLoopbackAddress())
                   {
                	   ip = inetAddress.getHostAddress().toString();
                   }
               }
           }
        }
        catch (SocketException ex){
        	ex.printStackTrace();
        }
        return ip;
        
    }



    public static String getIPAddress(Context context) {
        @SuppressLint("MissingPermission")
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                @SuppressLint("WifiManagerLeak")
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                @SuppressLint("MissingPermission")
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intToIp(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
            return "当前无网络连接,请在设置中打开网络";
        }
        return null;
    }

    /**
     * 解析域名获取IP 不要加http前缀单纯域名 如：www.xxx.com
     * @param host
     * @return
     */
    public static String parseHostGetIPAddressName(String host) {
        String hostAddress = null;
        try {
            InetAddress inetAddressArr = InetAddress.getByName(host);
            hostAddress = inetAddressArr.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return hostAddress;
    }

    /*
     * 判断ip是否在一个网段(局域网)
     * 用ip地址逻辑且子网掩码
     */
    public static boolean isIPAtSameSection(Context mContext,String ip1, String ip2) {
        if (TextUtils.isEmpty(ip1) || TextUtils.isEmpty(ip2)) {
            return false;
        }
        ip1 = ip1.trim();
        ip2 = ip2.trim();
        String subnetmask = getSubnetMask(mContext).trim();
        String[] ip1s = new String[4];
        String[] ip2s = new String[4];
        String[] subnetmasks = new String[4];
        String[] ipResult1s = new String[4];
        String[] ipResult2s = new String[4];
        ip1s = ip1.split("\\.");
        ip2s = ip2.split("\\.");
        subnetmasks = subnetmask.split("\\.");
        for (int i = 0; i < ip1s.length; ++i) {
            ipResult1s[i] = String.valueOf(Integer.parseInt(ip1s[i]) & Integer.parseInt(subnetmasks[i]));
        }
        for (int i = 0; i < ip2s.length; ++i) {
            ipResult2s[i] = String.valueOf(Integer.parseInt(ip2s[i]) & Integer.parseInt(subnetmasks[i]));
        }
        String newIp1 = ipResult1s[0] + ipResult1s[1] + ipResult1s[2] + ipResult1s[3];
        String newIp2 = ipResult2s[0] + ipResult2s[1] + ipResult2s[2] + ipResult2s[3];
        if (newIp1 != null && newIp2 != null && newIp1.equals(newIp2)) {
            return true;
        }
        return false;
    }


    // 返回当前手机网卡的子网掩码
    private static String getSubnetMask(Context mContext) {
        @SuppressLint("WifiManagerLeak")
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(mContext.WIFI_SERVICE);
        @SuppressLint("MissingPermission")
        DhcpInfo dhcp = wifiManager.getDhcpInfo();
        String ret = intToIp(dhcp.netmask);
        return ret;
    }

    private static String intToIp(int i) {
        return (i & 255) + "." + (i >> 8 & 255) + "." + (i >> 16 & 255) + "." + (i >> 24 & 255);
    }

    public static boolean startPing(String ip) {
        boolean isexist = false;
        Process process = null;

        try {
            process = Runtime.getRuntime().exec("ping -c 1 -i 0.5 -W 1 " + ip);
            int status = process.waitFor();
            if (status == 0) {
                isexist = true;
            } else {
                isexist = false;
            }
        } catch (IOException e) {
            isexist = false;
        } catch (InterruptedException e) {
            isexist = false;
        } finally {
            process.destroy();
        }
        return isexist;
    }
}
